package com.yunshipei.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yunshipei.EnterApplication;
import com.yunshipei.enterplorer.R;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import io.rong.app.model.SortModelHaveCheck;
import io.rong.app.utils.StringUtilSub;

public class SeekContactAdapter extends BaseAdapter implements SectionIndexer {

    private List<SortModelHaveCheck> list = null;
    private Context mContext;
    private ViewHolder viewHolder = null;
    private LruCache<String, BitmapDrawable> mMemoryCache;
    private Drawable drawable;

    public SeekContactAdapter(Context mContext, List<SortModelHaveCheck> list) {
        this.mContext = mContext;
        this.list = list;
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 20;
        mMemoryCache = new LruCache<String, BitmapDrawable>(cacheSize) {

            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                if (value != null) {
                    return value.getBitmap().getByteCount();
                }
                return 0;
            }
        };
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<SortModelHaveCheck> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public int getCount() {
        return this.list.size();
    }

    public Object getItem(int position) {
        return list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup arg2) {
        final SortModelHaveCheck mContent = list.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_sort_rongcloud_listview, null);
            viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);    //字母
            viewHolder.nameTV = (TextView) view.findViewById(R.id.name);        //姓名
            viewHolder.positionTV = (TextView) view.findViewById(R.id.position);            //职位
            viewHolder.avatar = (ImageView) view.findViewById(R.id.avatar);            //头像
            viewHolder.avatarText = (TextView) view.findViewById(R.id.avatarText);
            viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox1);        //选中状态
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        int section = getSectionForPosition(position);

        // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if (position == getPositionForSection(section)) {
            viewHolder.tvLetter.setVisibility(View.VISIBLE);
            viewHolder.tvLetter.setText(mContent.getSortModel().getSortLetters());
        } else {
            viewHolder.tvLetter.setVisibility(View.GONE);
        }

        viewHolder.nameTV.setText(substringFixedStr(this.list.get(position).getSortModel().getUserInfo().getName(), 8));
        viewHolder.positionTV.setText(substringFixedStr(this.list.get(position).getSortModel().getUserInfo().getPosition(),8));
//        viewHolder.positionTV.setText(this.list.get(position).getSortModel().getUserInfo().getPosition());
        if (StringUtilSub.isChinese(this.list.get(position).getSortModel().getUserInfo().getName())) {
            viewHolder.avatarText.setText(getEndword(this.list.get(position).getSortModel().getUserInfo().getName()));
        } else {
            viewHolder.avatarText.setText(this.list.get(position).getSortModel().getUserInfo().getName().substring(0, 1).toString().toUpperCase());
        }
        viewHolder.avatar.setImageResource(MyListViewAdapter.person_logos[position % MyListViewAdapter.person_logos.length]);
        viewHolder.avatar.setTag(this.list.get(position).getSortModel().getUserInfo().getUuid());
        //设置checkbox是否被选中
        boolean checked = list.get(position).getStatus();
        viewHolder.checkBox.setChecked(checked);

        String key1 = this.list.get(position).getSortModel().getUserInfo().getAvatar();
        if (!"notimage".equals(key1) && key1 != null) {
            drawable = getBitmapFromMemoryCache(this.list.get(position).getSortModel().getUserInfo().getAvatar());
            viewHolder.avatarText.setVisibility(View.GONE);
        } else {
            viewHolder.avatarText.setVisibility(view.VISIBLE);
        }
        if (drawable != null) {
            viewHolder.avatar.setImageDrawable(drawable);
        } else {
            if (!"notimage".equals(key1) && key1 != null) {
                String imgUrl = list.get(position).getSortModel().getUserInfo().getAvatar();
                Glide.with((Activity) mContext).load(imgUrl).into(viewHolder.avatar);
            }
        }

        return view;

    }


    /**
     * 将一张图片存储到LruCache中。
     *
     * @param key      LruCache的键，这里传入图片的URL地址。
     * @param drawable LruCache的值，这里传入从网络上下载的BitmapDrawable对象。
     */
    public void addBitmapToMemoryCache(String key, BitmapDrawable drawable) {
        if (!"notimage".equals(key) && key != null) {
            if (getBitmapFromMemoryCache(key) == null) {
                mMemoryCache.put(key, drawable);
            }
        }
    }

    /**
     * 从LruCache中获取一张图片，如果不存在就返回null。
     *
     * @param key LruCache的键，这里传入图片的URL地址。
     * @return 对应传入键的BitmapDrawable对象，或者null。
     */
    public BitmapDrawable getBitmapFromMemoryCache(String key) {
        return mMemoryCache.get(key);
    }

    /**
     * 异步下载图片的任务。
     *
     * @author guolin
     */
    class BitmapWorkerTask extends AsyncTask<String, Void, BitmapDrawable> {

        private ImageView mImageView;
        private String imageUrl;
        private String uuidString;

        public BitmapWorkerTask(ImageView imageView) {
            mImageView = imageView;
        }

        @Override
        protected BitmapDrawable doInBackground(String... params) {
            imageUrl = params[0];
            uuidString = params[1];
            // 在后台开始下载图片  
            Bitmap bitmap = downloadBitmap(imageUrl);
            if (bitmap != null) {
                BitmapDrawable drawable = new BitmapDrawable(EnterApplication.getApp().getResources(), bitmap);
                addBitmapToMemoryCache(uuidString, drawable);
                return drawable;
            }
            return null;
        }

        @Override
        protected void onPostExecute(BitmapDrawable drawable) {
            if (mImageView != null && drawable != null && mImageView.getTag().equals(uuidString)) {
                mImageView.setImageDrawable(drawable);
            }
        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }

    }

    final static class ViewHolder {
        TextView tvLetter, avatarText;//字母
        TextView nameTV, positionTV;
        ImageView avatar;
        CheckBox checkBox;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return list.get(position).getSortModel().getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = list.get(i).getSortModel().getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 提取英文的首字母，非英文字母用#代替。
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        String sortStr = str.trim().substring(0, 1).toUpperCase();
        // 正则表达式，判断首字母是否是英文字母
        if (sortStr.matches("[A-Z]")) {
            return sortStr;
        } else {
            return "#";
        }
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    /**
     * 截取字符串
     *
     * @param originalStr
     * @return
     */
    public static String getEndword(String originalStr) {
        String endWord;
        if (originalStr != null) {
            int len = originalStr.length();
            endWord = originalStr.substring(len - 1, len);
            return endWord;
        } else {
            return "";
        }
    }

    /**
     * @param originalStr 被截取字符串
     * @param subLen      字符串长度标准
     * @return
     */
    private String substringFixedStr(String originalStr, int subLen) {
        String str = null;
        if (originalStr == null) {
            return str = "";
        } else if (originalStr.equals("") || originalStr.equals("null")) {
            str = "";
        } else {
            int strLen = originalStr.length();
            if (strLen > subLen) {
                str = originalStr.substring(0, subLen);
            } else {
                return originalStr;
            }
        }
        return str;
    }

    public void setItemChecked(int positin) {
        viewHolder.checkBox.setChecked(true);
    }


}
